<template>
    <div class="sdy-login">
        <SdyHeader title="啥都有 ~ 登录" back></SdyHeader>
        <van-form class="login-from" @submit="submitHandler">
            <van-cell-group inset>
                <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
                    :rules="[{ required: true, message: '请填写用户名', pattern: /\w{6,12}/ }]" />
                <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
            </van-cell-group>
            <div>
                还没有账号,<router-link to="/register">去注册</router-link>
            </div>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    提交
                </van-button>
            </div>
        </van-form>
    </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { loginApi } from '@/api/users'
import { Toast } from 'vant';
import { useRouter, type Router } from 'vue-router';
//准备数据
const username = ref<string>('')
const password = ref<string>('')

const $router: Router = useRouter()

//实现登录
const submitHandler = async () => {
    // console.log('登录');
    const res = await loginApi(username.value, password.value)
    // console.log(res);
    // 判断密码是否正确
    if (((res as unknown) as { code: string }).code === '200') {
        Toast({
            message: '登录成功',
            icon: 'passed',
        });
        // 存储token和userid
        window.localStorage.setItem('token', res.data.token)
        window.localStorage.setItem('userid', res.data.userid)
        // 登录成功跳转到首页
        setInterval(() => {
            $router.push({ path: '/home' })
        }, 2000)
        return
    } else {
        Toast({
            message: '用户名密码错误',
            icon: 'warning-o',
        });
    }
}
</script>
<style scoped lang="scss">
.sdy-login {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    >.login-from {
        border: 1px solid #333;
        border-radius: 10px;
    }
}
</style>